package network;

import java.io.IOException;
import java.net.DatagramPacket;

public class UdpUtil {

	/** Converts an object to an array of bytes . Uses the Logging utilities in j2sdk1.4 for 
	* reporting exceptions. 
	* @param object the object to convert. 
	* @return the associated byte array. 
	*/ 
	public static byte[] toBytes(Object object){ 
		try {
			java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); 
			java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
			oos.writeObject(object);
			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}		
		return null;
	} 

	/** Converts an array of bytes back to its constituent object. The input array is assumed to 
	* have been created from the original object. Uses the Logging utilities in j2sdk1.4 for 
	* reporting exceptions. 
	* @param bytes the byte array to convert. 
	* @return the associated object. 
	*/ 
	public static Object toObject(byte[] bytes){ 
		Object object = null;
		try {
			object = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes)).readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return object; 
	}
	
	public static Object toObject(DatagramPacket packet){
		byte[] bytes = packet.getData();
		return UdpUtil.toObject(bytes);
	}
	
}
